package org.eclipse.stp.policy_builder.model.source.wizards.ui;

import java.util.Iterator;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.stp.policy_builder.model.source.ParameterMap;
import org.eclipse.stp.policy_builder.model.source.SourceParameter;
import org.eclipse.stp.policy_builder.model.source.SourceType;
import org.eclipse.stp.policy_builder.model.source.types.AbstractParamType;
import org.eclipse.stp.policy_builder.model.source.types.BoolParameter;
import org.eclipse.stp.policy_builder.model.source.types.StringParameter;
import org.eclipse.stp.policy_builder.model.source.types.UrlParameter;
import org.eclipse.stp.policy_builder.util.PolicyBuilderLog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class SourceParameterPage extends WizardPage{
	private Composite container;
	private SourceType type;
	
	public SourceParameterPage(){
		super("inputParameters");
		setTitle("Provide Parameter info :");
		setDescription("Following parameters are required to load the Message....");
	}
	
	@SuppressWarnings("restriction")
	public void createControl(Composite parent) {
		// TODO Auto-generated method stub
		  if(container!=null){
			  container.dispose();
		  }
		  container = new Group(parent, SWT.V_SCROLL);
	      final GridLayout gridLayout = new GridLayout();
	      gridLayout.numColumns = 3;
	      container.setLayout(gridLayout);
	      setControl(container);
	      
	      final Label label = new Label(container, SWT.WRAP);
	      final GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
	      gridData.horizontalSpan = 3;
	      label.setLayoutData(gridData);
	      
	      SourceType type = getSelectedTypes();
	      this.type = type ;
	      
	      label.setText("Parameters to be provided for the Source Provider : ["+type.getClassName()
	            + " ] to load the Messages");
		
	      	      
	      if(type!=null && type.getParameterContainer().getSize() > 0){
	    	  ParameterMap map = type.getParameterContainer();
	    	  Iterator<String> it = map.getKeySet();
	  		while(it.hasNext()){
	  			String key = it.next();
	  			SourceParameter param = map.getValue(key);
	  			createParameterRows(container, param);
	  		}
	    	  
	      }
	}
	@Override
	public void setPreviousPage(IWizardPage page) {
		// TODO Auto-generated method stub
		setControl(null);
		super.setPreviousPage(page);
	}
	
	public void printMap(ParameterMap map){
		Iterator<String> it = map.getKeySet();
		while(it.hasNext()){
			String key = it.next();
			SourceParameter param = map.getValue(key);
			System.out.println("Param Key : " + key);
			System.out.println("Param Value : " +param.getParameterValue());
		}
	}
	
	public ParameterMap getParameters(){
		if(type != null)
			return this.type.getParameterContainer();
		
		return null;
	}
	
	private void createParameterRows(Composite container,SourceParameter param){
		AbstractParamType type = param.getParameterType();
		//need to handle errors
		type.createTypeControl(container);
		type.getKeyLabel().setText(param.getParameterName());
		if(type instanceof StringParameter){
			createControlRow(param,(StringParameter) type);
		}
		else if(type instanceof UrlParameter){
			createControlRow(param,(UrlParameter) type);
		}
		else if(type instanceof BoolParameter){
			createControlRow(param,(BoolParameter) type);
		}
	}
	
	
	@SuppressWarnings("restriction")
	private void createControlRow(SourceParameter param,StringParameter type){
		String value = param.getParameterValue();
		if(value!=null){
			type.getParamInputText().setText(value);
		}
		System.out.println(param);
		final SourceParameter sParam = param ;
		final Text paramText= type.getParamInputText();
		
		paramText.addModifyListener(new ModifyListener(){
			@Override
			public void modifyText(ModifyEvent evnt) {
				// TODO Auto-generated method stub
				sParam.setValue(paramText.getText());
				
			}
		});
	}
	
	@SuppressWarnings("restriction")
	private void createControlRow(SourceParameter param,UrlParameter type){
		String value = param.getParameterValue();
		if(value!=null){
			type.getInputText().setText(value);
		}
		final Button browseButton = type.getBrowseButton();
		final Text pathText = type.getInputText();
		browseButton.addSelectionListener(new SelectionAdapter() {
	         public void widgetSelected(SelectionEvent e) {
	             browseForSourceFile(pathText);
	          }
	       });
		
		final SourceParameter sParam = param ;
		pathText.addModifyListener(new ModifyListener(){
			@Override
			public void modifyText(ModifyEvent evnt) {
				// TODO Auto-generated method stub
				sParam.setValue(pathText.getText());
			}
		});
		
	}
	
	private void createControlRow(SourceParameter param,BoolParameter type){
		//type.getInputText().setText(param.getParameterValue());
		String value = param.getParameterValue();
		if(value!=null)
			type.getCheckButton().setSelection(new Boolean(value));
		
		final Button checkButton = type.getCheckButton();
		final SourceParameter sParam = param ;
		
		checkButton.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e) {
	            boolean status = checkButton.getSelection();
	            String statusStr = Boolean.toString(status);
	            sParam.setValue(statusStr);
	         }
		});
		
		
	}
	
	protected void browseForSourceFile(Text textField) {
	      IPath path = browse(null,false);
	      if (path == null)
	         return;
	     /* IPath rootLoc = ResourcesPlugin.getWorkspace().getRoot().getLocation();
	      if (rootLoc.isPrefixOf(path))
	         path = path.setDevice(null).removeFirstSegments(rootLoc.segmentCount());
	      */
	      textField.setText(path.toString());
	 }
	
	private IPath browse(IPath path, boolean mustExist) {
	      FileDialog dialog = new FileDialog(getShell(), mustExist ? SWT.OPEN : SWT.SAVE);
	      if (path != null) {
	         if (path.segmentCount() > 1)
	            dialog.setFilterPath(path.removeLastSegments(1).toOSString());
	         if (path.segmentCount() > 0)
	            dialog.setFileName(path.lastSegment());
	      }
	      String result = dialog.open();
	      if (result == null)
	         return null;
	      return new Path(result);
	   }
	
	
	private SourceType getSelectedTypes(){
		
		return ((PolicyBuilderWizard) getWizard()).getSelectedTypes();
	}
	
	
}
